package com.bowlong.third.grizzly;

import java.io.DataInput;
import java.io.IOException;
import java.io.InputStream;

import org.glassfish.grizzly.Buffer;

public class GrizzlyInputStream extends InputStream implements DataInput {

	final Buffer buffer;

	public GrizzlyInputStream(Buffer buffer) {
		this.buffer = buffer;
	}

	@Override
	public void readFully(byte[] b) throws IOException {
		buffer.get(b);
	}

	@Override
	public void readFully(byte[] b, int off, int len) throws IOException {
		buffer.get(b, off, len);
	}

	@Override
	public int skipBytes(int n) throws IOException {
		int p = buffer.position();
		buffer.position(p + n);
		return buffer.position();
	}

	@Override
	public boolean readBoolean() throws IOException {
		return buffer.get() != 0;
	}

	@Override
	public byte readByte() throws IOException {
		return buffer.get();
	}

	@Override
	public int readUnsignedByte() throws IOException {
		return buffer.get() & 0xFF;
	}

	@Override
	public short readShort() throws IOException {
		return buffer.getShort();
	}

	@Override
	public int readUnsignedShort() throws IOException {
		int ch1 = buffer.get();
		int ch2 = buffer.get();
		return (ch1 << 8) + (ch2 << 0);
	}

	@Override
	public char readChar() throws IOException {
		return buffer.getChar();
	}

	@Override
	public int readInt() throws IOException {
		return buffer.getInt();
	}

	@Override
	public long readLong() throws IOException {
		return buffer.getLong();
	}

	@Override
	public float readFloat() throws IOException {
		return buffer.getFloat();
	}

	@Override
	public double readDouble() throws IOException {
		return buffer.getDouble();
	}

	@Override
	public String readLine() throws IOException {
		throw new IOException("NoSuchMethodException");
	}

	@Override
	public String readUTF() throws IOException {
		int len = buffer.getInt();
		byte[] bs = new byte[len];
		buffer.get(bs);
		return new String(bs, "UTF-8");
	}

	@Override
	public int read() throws IOException {
		return buffer.get();
	}

	public int postion() {
		return buffer.position();
	}

	public void postion(int pos) {
		buffer.position(pos);
	}

	@Override
	public void mark(int readlimit) {
		buffer.mark();
	}

	@Override
	public void reset() {
		buffer.reset();
	}

	@Override
	public int available() throws IOException {
		return buffer.limit() - buffer.position();
	}

}
